'use client';

import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react';

// Define the shape of our shared data
interface SharedData {
  userInfo: {
    name: string;
    email: string;
  } | null;
  theme: 'light' | 'dark';
  notifications: string[];
}

// Define the context type
interface SharedDataContextType extends SharedData {
  updateUserInfo: (info: SharedData['userInfo']) => void;
  toggleTheme: () => void;
  addNotification: (message: string) => void;
  clearNotifications: () => void;
}

// Create the context
const SharedDataContext = createContext<SharedDataContextType | undefined>(undefined);

// Provider component
export const SharedDataProvider = ({ children }: { children: ReactNode }) => {
  const [userInfo, setUserInfo] = useState<SharedData['userInfo']>(null);
  const [theme, setTheme] = useState<'light' | 'dark'>('light');
  const [notifications, setNotifications] = useState<string[]>([]);

  // Load data from localStorage on mount
  useEffect(() => {
    const savedUserInfo = localStorage.getItem('userInfo');
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | null;
    
    if (savedUserInfo) {
      try {
        setUserInfo(JSON.parse(savedUserInfo));
      } catch (e) {
        console.error('Failed to parse userInfo', e);
      }
    }
    
    if (savedTheme) {
      setTheme(savedTheme);
    }
  }, []);

  // Save to localStorage when data changes
  useEffect(() => {
    if (userInfo) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    }
  }, [userInfo]);

  useEffect(() => {
    localStorage.setItem('theme', theme);
  }, [theme]);

  // Context methods
  const updateUserInfo = (info: SharedData['userInfo']) => {
    setUserInfo(info);
  };

  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  };

  const addNotification = (message: string) => {
    setNotifications(prev => [...prev, message]);
  };

  const clearNotifications = () => {
    setNotifications([]);
  };

  const value = {
    userInfo,
    theme,
    notifications,
    updateUserInfo,
    toggleTheme,
    addNotification,
    clearNotifications
  };

  return (
    <SharedDataContext.Provider value={value}>
      {children}
    </SharedDataContext.Provider>
  );
};

// Hook to use the shared data context
export const useSharedData = () => {
  const context = useContext(SharedDataContext);
  if (context === undefined) {
    throw new Error('useSharedData must be used within a SharedDataProvider');
  }
  return context;
};